package com.simafei.flow.core.common;

import com.simafei.flow.core.FlowConstants;
import com.simafei.flow.core.func.Funcs;
import org.mvel2.MVEL;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author fengpengju
 */
public class ExpressionExecutor {

    public static Object execute(String expression, Map<String, Object> params) {
        // 复制一个新Map出来，不影响原有的Map
        Map<String, Object> execParam = new HashMap<>(params);
        execParam.put(FlowConstants.FUNC, Funcs.INSTANCE);
        execParam.putIfAbsent(FlowConstants.HAS_RESULT, FlowConstants.YES);
        Serializable serializable = MVEL.compileExpression(expression);
        return MVEL.executeExpression(serializable, execParam);
    }

    public static Object execute(String expression, Map<String, Object> params, Set<String> usingFields) {
        // 复制一个新Map出来，不影响原有的Map
        Map<String, Object> execParam = new HashMap<>(params);
        execParam.put(FlowConstants.FUNC, Funcs.INSTANCE);
        for (String usingField : usingFields) {
            // 避免MVEL执行报找不到变量的错误
            execParam.putIfAbsent(usingField, null);
        }
        execParam.putIfAbsent(FlowConstants.HAS_RESULT, FlowConstants.YES);
        Serializable serializable = MVEL.compileExpression(expression);
        return MVEL.executeExpression(serializable, execParam);
    }
}
